/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package easybooking.clients.gui;

import easybooking.data.Airline;
import easybooking.data.Airport;
import easybooking.data.Customer;
import easybooking.data.Plane;
import easybooking.data.Type;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.awt.event.ActionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreePath;

/**
 *
 * @author tim
 */
public class EBInterface implements ActionListener, TreeSelectionListener {

    public static void main(String args[]) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                createAndShowGUI();
            }
        });
    }
    private JMenuBar mainMenuBar;
    private JMenu fileJMenu;
    private JMenuItem exit;
    private JFrame clientMainFrame;
    private JPanel contentPanel;
    private JPanel mainPanel;
    private JSplitPane splitPane;
    private JPanel buttonPanel;
    private JScrollPane scrollPane;
    private EBInterfaceClient ebic = new EBInterfaceClient();
    private EBMenuTree easyBookingMenuTree;
    private EBInterfaceConfigDialog ebicd = new EBInterfaceConfigDialog(this);
    private CustomerForm cf = new CustomerForm(this);
    private CustomerCreateDialog ccd = new CustomerCreateDialog(this);
    private CustomerEditDialog ced = new CustomerEditDialog(this);
    private TypeForm tf = new TypeForm(this);
    private TypeCreateDialog tcd = new TypeCreateDialog(this);
    private TypeEditDialog ted = new TypeEditDialog(this);
    private AirportForm airpf = new AirportForm(this);
    private AirportCreateDialog airpcd = new AirportCreateDialog(this);
    private AirportEditDialog airped = new AirportEditDialog(this);
    private PlaneForm pf = new PlaneForm(this);
    private PlaneCreateDialog pcd = new PlaneCreateDialog(this);
    private PlaneCreateDialogTypeSelect pcdts = new PlaneCreateDialogTypeSelect(this);
    private PlaneCreateDialogAirlineSelect pcdas = new PlaneCreateDialogAirlineSelect(this);
    private AirlineForm airlf = new AirlineForm(this);
    private AirlineCreateDialog airlcd = new AirlineCreateDialog(this);
    private AirlineEditDialog airled = new AirlineEditDialog(this);
    private FlightForm ff =  new FlightForm(this);


    public EBInterface() {
        //new EasyBookingInterfaceConfig(this);
        //this.createAndShowGUI();
    }

    public static void createAndShowGUI() {
        EBInterface ebi = new EBInterface();
        ebi.createFrame();
        ebi.setServer();
    }

    public void createFrame() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception exc) {
            System.err.println("Error loading L&F: " + exc);
        }

        clientMainFrame = new JFrame("EasyBooking Client");
        clientMainFrame.setDefaultLookAndFeelDecorated(true);
        clientMainFrame.setPreferredSize(new Dimension(1000, 800));
        clientMainFrame.setJMenuBar(this.createMenuBar());
        clientMainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        clientMainFrame.getContentPane().add(createSplitPane());
        clientMainFrame.setResizable(true);
        clientMainFrame.setLocationRelativeTo(null);
        clientMainFrame.pack();
        clientMainFrame.setVisible(true);



    }
    // Creates the Menu Bar

    private JMenuBar createMenuBar() {

        mainMenuBar = new JMenuBar();
        fileJMenu = new JMenu("File");
        exit = new JMenuItem("Exit");

        exit.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        fileJMenu.add(exit);
        mainMenuBar.add(fileJMenu);
        return mainMenuBar;
    }

    private JSplitPane createSplitPane() {
        // creates the split pane and adds the tree manu and the main panel
        splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        splitPane.setLeftComponent(this.createTreeMenu());
        splitPane.setRightComponent(this.createStartPanel());
        return splitPane;
    }

    public void setRightPanel(JPanel p) {
        splitPane.setRightComponent(p);
        splitPane.repaint();
        clientMainFrame.getContentPane().repaint();
        clientMainFrame.repaint();
    }

    // Creates the scroll pane and adds the menu tree
    private JScrollPane createTreeMenu() {

        // Gets the singelton easyBookingMenuTree object
        easyBookingMenuTree = EBMenuTree.EasyBookingMenuTree(this);

        // Expand all nodes
        easyBookingMenuTree.expandAll();

        // Creates the
        scrollPane = new JScrollPane(easyBookingMenuTree);
        return scrollPane;
    }

    // Creates the ConfigPanel Form
    private JPanel createStartPanel() {
        mainPanel = new JPanel();

        // Sets the border
        mainPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("Easybooking Client "),
                BorderFactory.createEmptyBorder(20, 20, 20, 20)));

        // Sets the layout of the mainPanel
        mainPanel.setLayout(new GridBagLayout());
        GridBagLayout gbl = new GridBagLayout();

        // Places the GUI elements in the layout using addComponent                                           x, y, w, h, wx, wy       
        JLabel lblServerHost = new JLabel("StartPanel:");
        addComponent(mainPanel, gbl, lblServerHost, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 0, 0, 1, 1, 0, 0);

        JTextField txfServerHost = new JTextField(20);
        addComponent(mainPanel, gbl, txfServerHost, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 0, 1, 1, 0, 0);

        return mainPanel;
    }

    // Creates the button panel
    public JPanel createButtonPanel() {
        buttonPanel = new JPanel();


        // Sets the buttons the same size
        //btnOk.setPreferredSize(btnCancel.getPreferredSize());

        // Registrate action listeners


        return buttonPanel;
    }

    // Adds the elements to the layout
    static void addComponent(Container cont, GridBagLayout gbl, Component c, int fill, int anchor, int x, int y, int width, int hight, double weightx, double weighty) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = fill;
        gbc.anchor = anchor;
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.gridwidth = width;
        gbc.gridheight = hight;
        gbc.weightx = weightx;
        gbc.weighty = weighty;
        gbc.insets = new Insets(10, 10, 10, 10);
        //gbl.setConstraints(c, gbc);
        cont.add(c, gbc);


    }

    private void setServer() {
        ebicd.createAndShowDialog(); 
    }

    // testing
    public EBInterfaceClient getInterfaceClient() {
        return ebic;
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("connectToServer")) {
            if(ebic.initServerConnection(ebicd.getHostname())){
                JOptionPane.showMessageDialog(null, "Server connection sucessfull");
                 ebicd.dispose();
            }
            else {
                JOptionPane.showMessageDialog(null, "Server connection failed");
            }   
        }

        if (e.getActionCommand().equals("createCustomer")) {


            ccd.createAndShowDialog();
        }

        if (e.getActionCommand().equals("customerCreateDialogOk")) {

            // validate input of the zip field
            try {

                int x = Integer.parseInt(ccd.getZip());
            } catch (NumberFormatException nFE) {
                JOptionPane.showMessageDialog(null, "Please enter a correct Zip-Code");
            }

            // adds a new customer example data
            ebic.createCustomer(ccd.getFirstName(), ccd.getLastName(), ccd.getStreet(), ccd.getZip(), ccd.getCity());
            // gets and sets the whole table data
            cf.setTableData(ebic.getAllCustomers());
            // cleans the view
            cf.removeAll();
            // renews the cf
            cf.createAndShowForm();
            // shows the cf again
            this.setRightPanel(cf);
            // closes the ccd
            ccd.dispose();
        }
        if (e.getActionCommand().equals("editCustomer")) {
            if (cf.getSelectedCustomer() == null) {
                JOptionPane.showMessageDialog(null, "No customer selected");
            } else {
                try {
                    Customer c = (Customer) cf.getSelectedCustomer();
                    JOptionPane.showMessageDialog(null, "Editing: " + c.getFirstname() + " " + c.getLastname());
                    // pases the customer which should be edited
                    ced.createAndShowDialog(c);
                } catch (RemoteException ex) {
                    Logger.getLogger(EBInterface.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        if (e.getActionCommand().equals("customerEditDialogOk")) {

            // validate input of the zip field
            try {

                int x = Integer.parseInt(ced.getZip());
            } catch (NumberFormatException nFE) {
                JOptionPane.showMessageDialog(null, "Please enter a correct Zip-Code");
            }

            // adds a new customer example data
            ebic.updateCustomer(ced.getFirstName(), ced.getLastName(), ced.getStreet(), ced.getZip(), ced.getCity(), ced.getEditableCustomer());
            // gets and sets the whole table data
            cf.setTableData(ebic.getAllCustomers());
            // cleans the view
            cf.removeAll();
            // renews the cf
            cf.createAndShowForm();
            // shows the cf again
            this.setRightPanel(cf);
            // closes the ccd
            ced.dispose();
        }

        if (e.getActionCommand().equals("deleteCustomer")) {
            if (cf.getSelectedCustomer() == null) {
                JOptionPane.showMessageDialog(null, "No customer selected");
            } else {
                try {
                    Customer c = (Customer) cf.getSelectedCustomer();
                    JOptionPane.showMessageDialog(null, "Deleting: " + c.getFirstname() + " " + c.getLastname());
                    ebic.deleteCustomer(c);
                    cf.setTableData(ebic.getAllCustomers());
                    // cleans the view
                    cf.removeAll();
                    // renews the cf
                    cf.createAndShowForm();
                    // shows the cf again
                    this.setRightPanel(cf);
                } catch (RemoteException ex) {
                    Logger.getLogger(EBInterface.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        if (e.getActionCommand().equals("createType")) {
            tcd.createAndShowDialog();
        }

        if (e.getActionCommand().equals("typeCreateDialogOk")) {
            // validate input of the zip field
            try {
//                if (tcd.getRows().equals("")|| tcd.getColumns().equals("") || tcd.getName().equals("")){
//                JOptionPane.showMessageDialog(null, "Please enter all fields");
//                }

                int rows = Integer.parseInt(tcd.getRows());
                int columns = Integer.parseInt(tcd.getColumns());
            } catch (NumberFormatException nFE) {
                JOptionPane.showMessageDialog(null, "Please enter a correct number");
            }
            
            // adds a new Type example data
            ebic.createType(tcd.getName(), tcd.getRows(), tcd.getColumns());
            // gets and sets the whole table data
            tf.setTableData(ebic.getAllTypes());
            // cleans the view
            tf.removeAll();
            // renews the tf
            tf.createAndShowForm();
            // shows the tf again
            this.setRightPanel(tf);
            // closes the tcd
            tcd.dispose();

        }

        if (e.getActionCommand().equals("editType")) {
            if (tf.getSelectedType() == null) {
                JOptionPane.showMessageDialog(null, "No type selected");
            } else {
                try {
                    Type t = (Type) tf.getSelectedType();
                    JOptionPane.showMessageDialog(null, "Editing: " + t.getName());
                    // pases the type which should be edited
                    ted.createAndShowDialog(t);
                } catch (RemoteException ex) {
                    Logger.getLogger(EBInterface.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        if (e.getActionCommand().equals("typeEditDialogOk")) {
            // validate input of the zip field
            try {

                int rows = Integer.parseInt(ted.getRows());
                int columns = Integer.parseInt(ted.getColumns());
            } catch (NumberFormatException nFE) {
                JOptionPane.showMessageDialog(null, "Please enter a correct Number");
            }

            // adds a new customer example data
            ebic.updateType(ted.getName(), ted.getRows(), ted.getColumns(), ted.getEditableType());
            // gets and sets the whole table data
            tf.setTableData(ebic.getAllTypes());
            // cleans the view
            tf.removeAll();
            // renews the tf
            tf.createAndShowForm();
            // shows the ff again
            this.setRightPanel(tf);
            // closes the ted
            ted.dispose();
        }


        if (e.getActionCommand().equals("deleteType")) {
            if (tf.getSelectedType() == null) {
                JOptionPane.showMessageDialog(null, "No Type selected");
            } else {
                try {
                    Type t = (Type) tf.getSelectedType();
                    JOptionPane.showMessageDialog(null, "Deleting: " + t.getName());
                    ebic.deleteType(t);
                    tf.setTableData(ebic.getAllTypes());
                    // cleans the view
                    tf.removeAll();
                    // renews the cf
                    tf.createAndShowForm();
                    // shows the cf again
                    this.setRightPanel(tf);
                } catch (RemoteException ex) {
                    Logger.getLogger(EBInterface.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        if (e.getActionCommand().equals("createAirport")) {
            airpcd.createAndShowDialog();
        }

        if (e.getActionCommand().equals("airportCreateDialogOk")) {

            // adds a new Type example data
            ebic.createAirport(airpcd.getName(), airpcd.getInitials(), airpcd.getCity());
            // gets and sets the whole table data
            airpf.setTableData(ebic.getAllAirports());
            // cleans the view
            airpf.removeAll();
            // renews the airpf
            airpf.createAndShowForm();
            // shows the airpf again
            this.setRightPanel(airpf);
            // closes the airpcd
            airpcd.dispose();
        }

        if (e.getActionCommand().equals("editAirport")) {
            if (airpf.getSelectedAirport() == null) {
                JOptionPane.showMessageDialog(null, "No airport selected");
            } else {
                try {
                    Airport airp = (Airport) airpf.getSelectedAirport();
                    JOptionPane.showMessageDialog(null, "Editing: " + airp.getName());
                    // pases the type which should be edited
                    airped.createAndShowDialog(airp);
                } catch (RemoteException ex) {
                    Logger.getLogger(EBInterface.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        if (e.getActionCommand().equals("airportEditDialogOk")) {

            // adds a new airport example data
            ebic.updateAirport(airped.getName(), airped.getInitials(), airped.getCity(), airped.getEditableAirport());
            // gets and sets the whole table data
            airpf.setTableData(ebic.getAllAirports());
            // cleans the view
            airpf.removeAll();
            // renews the airpf
            airpf.createAndShowForm();
            // shows the airpf again
            this.setRightPanel(airpf);
            // closes the airped
            airped.dispose();
        }


        if (e.getActionCommand().equals("deleteAirport")) {
            if (airpf.getSelectedAirport() == null) {
                JOptionPane.showMessageDialog(null, "No airport selected");
            } else {
                try {
                    Airport airp = (Airport) airpf.getSelectedAirport();
                    JOptionPane.showMessageDialog(null, "Deleting: " + airp.getName());
                    ebic.deleteAirport(airp);
                    airpf.setTableData(ebic.getAllAirports());
                    // cleans the view
                    airpf.removeAll();
                    // renews the cf
                    airpf.createAndShowForm();
                    // shows the cf again
                    this.setRightPanel(airpf);
                } catch (RemoteException ex) {
                    Logger.getLogger(EBInterface.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        if (e.getActionCommand().equals("createPlane")) {
            //pcd.setType(null);
            pcd.createAndShowDialog();
        }

        if (e.getActionCommand().equals("PlaneCreateDialogTypeSelect")) {
            pcdts.setTableData(ebic.getAllTypes());
            pcdts.createAndShowDialog();
        }

        if (e.getActionCommand().equals("PlaneSelectType")) {
            pcd.setType((Type) pcdts.getSelectedType());

            pcdts.dispose();
        }

        if (e.getActionCommand().equals("PlaneCreateDialogAirlineSelect")) {
            pcdas.setTableData(ebic.getAllAirlines());
            pcdas.createAndShowDialog();
        }

        if (e.getActionCommand().equals("PlaneSelectAirline")) {
            pcd.setAirline((Airline) pcdas.getSelectedAirline());
            pcdas.dispose();
        }

        if (e.getActionCommand().equals("deletePlane")) {
            if (pf.getSelectedPlane() == null) {
                JOptionPane.showMessageDialog(null, "No plane selected");
            } else {
                try {
                    Plane p = (Plane) pf.getSelectedPlane();
                    JOptionPane.showMessageDialog(null, "Deleting: " + p.getName());
                    ebic.deletePlane(p);
                    pf.setTableData(ebic.getAllPlanes());
                    // cleans the view
                    pf.removeAll();
                    // renews the cf
                    pf.createAndShowForm();
                    // shows the cf again
                    this.setRightPanel(pf);
                } catch (RemoteException ex) {
                    Logger.getLogger(EBInterface.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        if (e.getActionCommand().equals("planeCreateDialogOk")) {
            try {
                // adds a new Type example data
                ebic.createPlane(pcd.getName(), pcd.getType().getTypeId(), pcd.getAirline().getAirlineId());
                // gets and sets the whole table data
                pf.setTableData(ebic.getAllPlanes());
                // cleans the view
                pf.removeAll();
                // renews the airpf
                pf.createAndShowForm();
                // shows the airpf again
                this.setRightPanel(pf);
                // closes the airpcd
                pcd.dispose();
            } catch (RemoteException ex) {
                Logger.getLogger(EBInterface.class.getName()).log(Level.SEVERE, null, ex);
            }
        }


        if (e.getActionCommand().equals("createAirline")) {
            airlcd.createAndShowDialog();
        }

        if (e.getActionCommand().equals("airlineCreateDialogOk")) {

            // adds a new Type example data
            ebic.createAirline(airlcd.getName(), airlcd.getInitials());
            // gets and sets the whole table data
            airlf.setTableData(ebic.getAllAirlines());
            // cleans the view
            airlf.removeAll();
            // renews the airpf
            airlf.createAndShowForm();
            // shows the airpf again
            this.setRightPanel(airlf);
            // closes the airpcd
            airlcd.dispose();
        }


        if (e.getActionCommand().equals("editAirline")) {
            if (airlf.getSelectedAirline() == null) {
                JOptionPane.showMessageDialog(null, "No airline selected");
            } else {
                try {
                    Airline airl = (Airline) airlf.getSelectedAirline();
                    JOptionPane.showMessageDialog(null, "Editing: " + airl.getName());
                    // pases the type which should be edited
                    airled.createAndShowDialog(airl);
                } catch (RemoteException ex) {
                    Logger.getLogger(EBInterface.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        if (e.getActionCommand().equals("airlineEditDialogOk")) {

            // adds a new airport example data
            ebic.updateAirline(airled.getName(), airled.getInitials(), airled.getEditableAirline());
            // gets and sets the whole table data
            airlf.setTableData(ebic.getAllAirlines());
            // cleans the view
            airlf.removeAll();
            // renews the airpf
            airlf.createAndShowForm();
            // shows the airpf again
            this.setRightPanel(airlf);
            // closes the airped
            airled.dispose();
        }


        if (e.getActionCommand().equals("deleteAirline")) {
            if (airlf.getSelectedAirline() == null) {
                JOptionPane.showMessageDialog(null, "No airline selected");
            } else {
                try {
                    Airline airl = (Airline) airlf.getSelectedAirline();
                    JOptionPane.showMessageDialog(null, "Deleting: " + airl.getName());
                    ebic.deleteAirline(airl);
                    airlf.setTableData(ebic.getAllAirlines());
                    // cleans the view
                    airlf.removeAll();
                    // renews the cf
                    airlf.createAndShowForm();
                    // shows the cf again
                    this.setRightPanel(airlf);
                } catch (RemoteException ex) {
                    Logger.getLogger(EBInterface.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }


    }

    public void valueChanged(TreeSelectionEvent e) {
        TreePath path = e.getNewLeadSelectionPath();

        Object a = path.getLastPathComponent().toString();

        if (a == "Customers") {

            // removes all old components
            cf.removeAll();
            // set table date
            cf.setTableData(ebic.getAllCustomers());
            // prepare form for displaying
            cf.createAndShowForm();
            // show cf in the right panel
            this.setRightPanel(cf);
        }

        if (a == "Types") {

            tf.removeAll();
            tf.setTableData(ebic.getAllTypes());
            tf.createAndShowForm();
            this.setRightPanel(tf);
        }
        if (a == "Airports") {
            airpf.removeAll();
            airpf.setTableData(ebic.getAllAirports());
            airpf.createAndShowForm();
            this.setRightPanel(airpf);
        }
        if (a == "Planes") {
            pf.removeAll();
            pf.setTableData(ebic.getAllPlanes());
            pf.createAndShowForm();
            this.setRightPanel(pf);
        }
        if (a == "Airlines") {
            airlf.removeAll();
            airlf.setTableData(ebic.getAllAirlines());
            airlf.createAndShowForm();
            this.setRightPanel(airlf);
        }
        if (a == "Flights") {
            ff.removeAll();
            ff.setTableData(ebic.getAllFlights());
            ff.createAndShowForm();
            this.setRightPanel(ff);
        }

        if (a == "EasyBooking") {
            this.setRightPanel(mainPanel);
        }
    }
}
